package org.example.emp.controller;

import org.example.emp.dto.DepartmentDto;
import org.example.emp.exception.SqlDataException;
import org.example.emp.pojo.Department;
import org.example.emp.pojo.Result;
import org.example.emp.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("departments")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    /**
     * 查询所有部门信息
     * */
    @GetMapping
    public Result all(){
        List<Department> departmentList = departmentService.list();
        if(departmentList.isEmpty()){
            return new Result<>(100 , "查询失败");
        }
        return new Result<>(0 , "查询成功" , departmentList);
    }

    /**
     * 根据id查询部门信息及其下所有员工的信息
     * */
    @GetMapping("{id}")
    public Result get(@PathVariable Integer id){
        DepartmentDto departmentDto = departmentService.getDepartmentAndEmployeeById(id);
        if(departmentDto == null){
            return new Result(100 , "查询错误");
        }
        return new Result<>(0 , "查询成功" , departmentDto);
    }

    /**
     * 根据id删除部门
     * 逻辑：
     * 1.删除部门信息
     * 2.部门下所有员工状态更改为异常，待从新分配部门后更改为正常
     * */
    @DeleteMapping("{id}")
    public Result deleteById(@PathVariable Integer id){
        boolean temp = departmentService.deletedDepartmentAndEmployeeById(id);
        if (temp){
            return new Result(0 , "删除成功");
        }
        return new Result(100 , "删除失败");
    }

    /**
     * 修改部门信息
     * */
    @PutMapping
    public Result update(@RequestBody Department department){
        boolean temp = departmentService.updateById(department);
        if (temp){
            return new Result(0 , "修改成功");
        }
        return new Result(100 , "修改失败");
    }

    /**
     * 添加部门信息
     * */
    @PostMapping
    public Result add(@RequestBody Department department){
        boolean temp = departmentService.save(department);
//        if (temp){
//            return new Result(0 , "添加成功");
//        }
        throw new SqlDataException("数据重复");
    }
}
